/**
 * jims
 */
package com.jims.master.modules.csm.service;

import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.csm.dao.*;
import com.jims.master.modules.csm.entity.*;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 消耗品库存管理Service
 * @author zhuq
 * @version 2017-03-10
 */
@Service
@Transactional(readOnly = true)
public class ExpStockService extends CrudService<ExpStockDao, ExpStock> {
    @Autowired
    private ExpClassDictDao expClassDictDao;
    @Autowired
    private ExpStorageDeptDao expStorageDeptDao;
    @Autowired
    private ExpImportMasterService expImportMasterService;
    @Autowired
    private ExpImportDetailService expImportDetailService;
    @Autowired
    private ExpImportMasterDao expImportMasterDao;
    @Autowired
    private ExpImportDetailDao expImportDetailDao;
    @Autowired
    private  ExpStockDao expStockDao;
    @Autowired
    private ExpExportMasterDao expExportMasterDao;
    @Autowired
    private ExpExportDetailDao expExportDetailDao;
    @Autowired
    private ExpExportService expExportService;
    @Autowired
    private ExpPriceDao expPriceDao;

	public ExpStock get(String id) {
		return super.get(id);
	}

	public List<ExpStock> findList(ExpStock expStock) {
		return super.findList(expStock);
	}

	public Page<ExpStock> findPage(Page<ExpStock> page, ExpStock expStock) {
		return super.findPage(page, expStock);
	}

	@Transactional(readOnly = false)
	public int save(ExpStock expStock) {
		return super.save(expStock);
	}

    /**
     * 对消入出库
     * @param list
     * @return
     * @author fengyg
     */
    @Transactional
    public int saveImpExp(List<ExpStock> list){
        int num = 0;
        if(null != list && list.size() > 0){
            ExpImportMaster importMaster = new ExpImportMaster();  //入库主记录
            importMaster.preInsert();
            importMaster.setStorageId(UserUtils.getUser().getOrgDept().getId());
            importMaster.setImportDate(list.get(0).getImportDate());
            importMaster.setSupplier(list.get(0).getSupplier());
            //importMaster.setImportClass(list.get(0).getImportClass());
            importMaster.setImportClass(DictUtils.getDictLabel(list.get(0).getImportClass(),"EXP_STOTARG_TYPE",""));  //入库类别转换
            importMaster.setAccountType(list.get(0).getAccountType());
            importMaster.updateOrgId();
            importMaster.setDocumentNo(expImportMasterService.createDocumentNo(importMaster));

            ExpExportMaster exportMaster = list.get(0).getExpExportMaster();  //出库主记录
            exportMaster.preInsert();
            exportMaster.setStorageId(UserUtils.getUser().getOrgDept().getId());
            exportMaster.setExportClass(DictUtils.getDictLabel(exportMaster.getExportClass(),"EXP_STOTARG_TYPE",""));  //出库类别转换
            exportMaster.setExportDate(list.get(0).getImportDate());
            exportMaster.setAccountType("");
            exportMaster.updateOrgId();
            exportMaster.setDocumentNo(expExportService.createDocumentNo(exportMaster));

            Double importAccountReceivable = 0.00;   //入库应付款
            Double exportAccountReceivable = 0.00;   //出库应收款
            for(int i = 0; i < list.size(); i++){
                ExpStock expStock = list.get(i);
                ExpImportDetail importDetail = new ExpImportDetail();   //入库明细记录
                importDetail.preInsert();
                importDetail.setMasterId(importMaster.getId());
                importDetail.setItemNo((i + 1) + "");
                importDetail.setExpCode(expStock.getExpCode());
                importDetail.setInfoId(expStock.getInfoId());
                importDetail.setPackageNum(expStock.getPackageNum());
                importDetail.setPackageSpec(expStock.getPackageSpec());
                importDetail.setPackageUnits(expStock.getPackageUnits());
                importDetail.setMinSpec(expStock.getMinSpec());
                importDetail.setMinUnits(expStock.getMinUnits());
                importDetail.setPurchasePrice(expStock.getPurchasePrice());
                importDetail.setDiscount(expStock.getDiscount());
                importDetail.setBatchNo(expStock.getBatchNo());
                importDetail.setExpireDate(expStock.getExpireDate());
                importDetail.setSterilizationMethod(expStock.getSterilizationMethod());
                importDetail.setSterilizationBatchNo(expStock.getSterilizationBatchNo());
                importDetail.setSterilizationDate(expStock.getSterilizationDate());
                importDetail.setQuantity(Integer.parseInt(expStock.getPackageNum()) * expStock.getQuantity() + "");
                importDetail.updateOrgId();
                int importDetailInsert = expImportDetailDao.insert(importDetail);  //插入入库明细
                if(importDetailInsert > 0){
                    num += importDetailInsert;
                }else{
                    return 0;
                }
                ExpPrice price = new ExpPrice();
                ExpInfo info = new ExpInfo();
                info.setId(importDetail.getInfoId());
                price.setExpInfo(info);
                price.setPackageSpec(importDetail.getPackageSpec());
                ExpPrice nowPrice = expPriceDao.getPriceByInfoPackageSpec(price);   //现行价格
                importAccountReceivable += expStock.getQuantity() * expStock.getPurchasePrice();  //计算入库应付款
                exportAccountReceivable += expStock.getQuantity() * nowPrice.getRetailPrice();    //计算出库应付款

                ExpExportDetail exportDetail = new ExpExportDetail();  //出库明细记录

                expStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
                expStock.updateOrgId();
                List<ExpStock> batchStockList = expStockDao.findByBatchNo(expStock);
                if(null != batchStockList && batchStockList.size() >0){  //库房里有该批次的消耗品
                    exportDetail.setInventory(batchStockList.get(0).getQuantity());  //出库后库存剩余数量
                }else{
                    exportDetail.setInventory(0.00);  //出库后库存剩余数量
                    //库房没有改批次的该消耗品，插入一条数据
                    expStock.preInsert();
                    expStock.setQuantity(0.00);
                    expStock.setDocumentNo(importMaster.getDocumentNo());
                    expStock.setImportMasterId(importMaster.getId());
                    int stockInsert = expStockDao.insert(expStock);
                    if(stockInsert > 0){
                        num += stockInsert;
                    }else{
                        return 0;
                    }
                }
                exportDetail.preInsert();
                exportDetail.setMasterId(exportMaster.getId());
                exportDetail.setItemNo((i + 1) + "");
                exportDetail.setInfoId(expStock.getInfoId());
                exportDetail.setExpCode(expStock.getExpCode());
                exportDetail.setPackageNum(expStock.getPackageNum());
                exportDetail.setPackageSpec(expStock.getPackageSpec());
                exportDetail.setPackageUnits(expStock.getPackageUnits());
                exportDetail.setMinSpec(expStock.getMinSpec());
                exportDetail.setMinUnits(expStock.getMinUnits());
                exportDetail.setBatchNo(expStock.getBatchNo());
                exportDetail.setExpireDate(expStock.getExpireDate());
                exportDetail.setSterilizationMethod(expStock.getSterilizationMethod());
                exportDetail.setSterilizationBatchNo(expStock.getSterilizationBatchNo());
                exportDetail.setSterilizationDate(expStock.getSterilizationDate());
                exportDetail.setPurchasePrice(nowPrice.getRetailPrice());
                exportDetail.setDiscount(expStock.getDiscount());
                exportDetail.setQuantity(Double.valueOf(importDetail.getQuantity()));
                exportDetail.updateOrgId();
                int exportDetailInsert = expExportDetailDao.insert(exportDetail);  //插入出库明细
                if(exportDetailInsert > 0){
                    num += exportDetailInsert;
                }else{
                    return 0;
                }
            }
            importMaster.setAccountReceivable(importAccountReceivable);
            int importMasterInsert = expImportMasterDao.insert(importMaster); //插入入库主记录
            if (importMasterInsert > 0) {
                num += importMasterInsert;
            } else {
                return 0;
            }
            exportMaster.setAccountReceivable(exportAccountReceivable);
            int exportMasterInsert = expExportMasterDao.insert(exportMaster);  //插入出库主记录
            if(exportMasterInsert > 0){
                num += exportMasterInsert;
            }else{
                return 0;
            }
        }else{   //没有数据
            return 0;
        }
        return num;
    }

	@Transactional(readOnly = false)
	public int delete(ExpStock expStock) {
		return super.delete(expStock);
	}

    /**
     * 库存量查询
     * @param page
     * @param expStock
     * @param expName
     * @param expType
     * @return
     */
    public Page<ExpStock> findExpList(Page<ExpStock> page, ExpStock expStock,String expName,String expType){
        expStock.updateOrgId();
        expStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
        expStock.setPage(page);
        if(!"".equals(expType) && expType !=null){
            expStock.setExpCode(expClassDictDao.get(expType).getClassCode());
        }
        expStock.setExpName(expName);
        page.setList(dao.findExpList(expStock));
        return page;
    }

    public ExpStock findExpByInfoId(ExpStock expStock){
        expStock=dao.findExpByInfoId(expStock);
        return expStock;
    }

    public Page<ExpStock> findExpListbat(Page<ExpStock> page, ExpStock expStock){
        expStock.updateOrgId();
        expStock.setStorageId(expStock.getStorageId());
        expStock.setPage(page);
        if(!"".equals(expStock.getExpType()) && expStock.getExpType() !=null){
            expStock.setExpCode(expClassDictDao.get(expStock.getExpType()).getClassCode());
        }
        page.setList(dao.findExpListbat(expStock));
        return page;
    }

    /*消耗品入库处理
     * @zhuq
     * 获取要入库的expList,分别插入expStock,expImportMaster,expImportDetail表
     * */
    @Transactional(readOnly = false)
    public String saveImportExp(List<ExpStock> expStockList){
        if(null != expStockList && expStockList.size() > 0){
            for (ExpStock stock : expStockList) {
                stock.setStorageId(UserUtils.getUser().getOrgDept().getId());
            }
        }
        int num=1;
        String printMasterId="";
        //组装expImportMaster数据
        ExpStock expStock=expStockList.get(0);
        ExpImportMaster expImportMaster=new ExpImportMaster();
        expImportMaster=expImportMasterService.createData(expStock);
        printMasterId=expImportMaster.getId();//获取打印主表ID
        //定义购买总金额
        Double allPrice=0.0;
        expImportMaster.setAccountReceivable(allPrice);
        expImportMaster.setDocumentNo(expImportMasterService.createDocumentNo(expImportMaster));
        num = num * expImportMasterDao.insert(expImportMaster);

        for(int i=0;i<expStockList.size();i++){
            //组装expImportDetail数据并保存
            ExpImportDetail expImportDetail=new ExpImportDetail();
            expImportDetail=expImportDetailService.createData(expStockList.get(i),i,expImportMaster.getId());
            num = num * expImportDetailDao.insert(expImportDetail);

            //判断一个库存的，一个消耗品的批号是否存在，若存在，直接加数量
            ExpStock expStockNew ;
            expStockNew=expStockList.get(i);
            expStockNew.setPackageNum(expImportDetail.getPackageNum());
            expStockNew.setDocumentNo(expImportMaster.getDocumentNo());
            expStockNew.updateOrgId();

            if(dao.findByBatchNo(expStockNew).size()>0){
                ExpStock expStockOld =new ExpStock();
                expStockOld = dao.findByBatchNo(expStockNew).get(0);
                //入库的大包装数量*包装数+已有库存量
                Double newQuantity = expStock.getQuantity() * Integer.parseInt(expStockNew.getPackageNum()) + expStockOld.getQuantity();
                allPrice = allPrice + expStock.getQuantity() * expStockNew.getPurchasePrice();
                expStockOld.setQuantity(newQuantity);
                expStockOld.setDocumentNo(expImportMaster.getDocumentNo());
                expStockOld.setImportMasterId(expImportMaster.getId());
                expStockOld.preUpdate();
                num = num * dao.update(expStockOld);
            }else {
                allPrice = allPrice + expStockNew.getPurchasePrice() * expStockNew.getQuantity();
                expStockNew.setQuantity(expStockNew.getQuantity() * Integer.parseInt(expStockNew.getPackageNum()));
                expStockNew.setImportMasterId(expImportMaster.getId());
                expStockNew.setSupplierId(expImportMaster.getSupplier());
                expStockNew.preInsert();
                num = num * dao.insert(expStockNew);
            }
        }
        expImportMaster.setAccountReceivable(allPrice);
        num = num * expImportMasterDao.update(expImportMaster);
        if(num>0){
            return printMasterId;
        }
        else {
            return "0";
        }
    }
    /**
     * 过期消耗品查找
     * @param expStock
     * @return
     */
    public Page<ExpStock> findExpStock(Page<ExpStock> page,ExpStock expStock){
        expStock.updateOrgId();
        expStock.setPage(page);
        page.setList(expStockDao.findExpStock(expStock));
        return page;
    }

    /**
     * 盘点的消耗品列表
     * @param
     * @return
     * update by CTQ AT 2017-07-07 10:34:06
     */
    public Page<ExpStock> findInventoryStockPage(Page<ExpStock> page,ExpInventoryCheck expInventoryCheck){
        List<ExpStock> list = handleExpStock(expInventoryCheck);
        page.setList(list);
        page.setCount(list.size());
        return page;
    }

    /**
     * 查询消耗品盘点记录
     * @param page
     * @param expInventoryCheck
     * @return
     * @author CTQ
     * @date 2017-07-05 18:53:17
     */
    public Page<ExpStock> findRecordPage(Page<ExpStock> page,ExpInventoryCheck expInventoryCheck){
        expInventoryCheck.setType("2");//已盘点过药品
        List<ExpStock> list = handleExpStock(expInventoryCheck);
        page.setList(list);
        page.setCount(list.size());
        return page;
    }

    /**
     * 处理查询条件公用方法
     * @param expInventoryCheck
     * @return
     * @author CTQ
     * @date 2017-07-07 10:33:41
     */
    private List<ExpStock> handleExpStock(ExpInventoryCheck expInventoryCheck){
        ExpStock expStock=new ExpStock();
        expStock.setExpName(null!=expInventoryCheck.getExpName()?expInventoryCheck.getExpName():"");
        expStock.updateOrgId();
        expStock.setStorageId(null!=UserUtils.getUser().getOrgDept()?UserUtils.getUser().getOrgDept().getId():"");
        expStock.setType(expInventoryCheck.getType());
        return expStockDao.findInventoryStock(expStock);
    }

    /**
     * 消耗品批量入库
     * @param stockList
     * @return
     * @author fengyg
     */
    @Transactional(readOnly = false)
    public int saveBatchImport(List<ExpStock> stockList) {
        int num = 0;
        if(null != stockList && stockList.size() > 0){
            ExpImportMaster importMaster = stockList.get(0).getExpImportMaster();
            importMaster.preInsert();
            importMaster.setDocumentNo(createImportDocumentNo());
            importMaster.setImportClass(DictUtils.getDictLabel(importMaster.getImportClass(), "EXP_STOTARG_TYPE", ""));
            importMaster.updateOrgId();
            int insert = expImportMasterDao.insert(importMaster);//保存入库主记录
            if(insert > 0){
                num += insert;
            }else{
                return 0;
            }
            for(int i = 0; i < stockList.size(); i++){
                //修改出库主记录的对应入库者、对应入库日期、对应入库主表ID三个字段
                ExpExportMaster exportMaster = expExportMasterDao.get(stockList.get(i).getExpExportMaster().getId());
                exportMaster.setImportOperator(UserUtils.getUser().getId());
                exportMaster.setImportDate(importMaster.getImportDate());
                exportMaster.setImportMasterId(importMaster.getId());
                exportMaster.preUpdate();
                int update = expExportMasterDao.update(exportMaster);//更新出库主记录
                if(update > 0){
                    num += update;
                }else{
                    return 0;
                }
                ExpImportDetail importdetail = stockList.get(i).getExpImportDetail();
                importdetail.preInsert();
                importdetail.setMasterId(importMaster.getId());
                importdetail.setItemNo(i+1 + "");
                importdetail.setPackageUnits(DictUtils.getDictValue(importdetail.getPackageUnits(),"SPEC_UNIT",""));
                importdetail.setMinUnits(DictUtils.getDictValue(importdetail.getMinUnits(),"SPEC_UNIT",""));
                importdetail.updateOrgId();
                int insertImpDetail = expImportDetailDao.insert(importdetail);//保存入库明细
                if(insertImpDetail > 0){
                    num += insertImpDetail;
                }else{
                    return 0;
                }
                ExpStock stock = stockList.get(i);
                stock.preInsert();
                stock.setStorageId(UserUtils.getUser().getOrgDept().getId());
                stock.setPackageUnits(DictUtils.getDictValue(stock.getPackageUnits(), "SPEC_UNIT", ""));
                stock.setMinUnits(DictUtils.getDictValue(stock.getMinUnits(), "SPEC_UNIT", ""));
                stock.updateOrgId();
                stock.setDocumentNo(importMaster.getDocumentNo());
                stock.setImportMasterId(importMaster.getId());
                stock.setSupplierId(importMaster.getSupplier());
                //判断库房里面是否有同批次同厂家同规格的该消耗品，如果有，直接加库存；如果没有，新增一条库存数据
                List<ExpStock> stockOlds = dao.findByBatchNo(stock);
                if(null != stockOlds && stockOlds.size() > 0){
                    ExpStock oldStock = stockOlds.get(0);
                    oldStock.setExpireDate(importdetail.getExpireDate());
                    oldStock.setQuantity(oldStock.getQuantity() + stockList.get(i).getQuantity());
                    oldStock.setDocumentNo(importMaster.getDocumentNo());
                    oldStock.setImportMasterId(importMaster.getId());
                    oldStock.preUpdate();
                    int updateStockQuantity = dao.update(oldStock);//更新库存
                    if(updateStockQuantity > 0){
                        num += updateStockQuantity;
                    }else{
                        return 0;
                    }
                }else{
                    int insertNewStock = dao.insert(stock);//保存库存
                    if(insertNewStock > 0){
                        num += insertNewStock;
                    }else{
                        return 0;
                    }
                }
            }
        }else{
            return -1;
        }
        return num;
    }

    /**
     * 根据库房id,infoId获取不同批次的库存大于0的list
     * @return
     * @author zhuq
     */
    public List<ExpStock> findByInfoId (ExpStock expStock){
        expStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
        expStock.updateOrgId();
        return dao.findByInfoId(expStock);
    }

    /**
     * 生成入库单号
     * @return
     * @author fengyg
     */
    public String createImportDocumentNo() {
        //根据库房获取入库单前缀
        ExpStorageDept expStorageDept = expStorageDeptDao.getByStorageCode(UserUtils.getUser().getOrgDept().getId());
        String documentNo = expStorageDept != null ? expStorageDept.getImportNoPrefix() : "";
        //获取当前日期
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        documentNo = documentNo + sdf.format(d);
        ExpImportMaster importMaster = new ExpImportMaster();
        importMaster.setDocumentNo(documentNo);
        importMaster.updateOrgId();
        //序号
        int i = expImportMasterDao.findDocumentNo(importMaster);
        String num = String.valueOf(i);
        String str = "0000";
        str = str.substring(0, 4 - num.length()) + num;
        documentNo = documentNo + str;
        return documentNo;
    }

    /**
     * 科室申领物品,库存数大于0的物品自动补全
     * @param q
     * @param limit
     * @return
     * @author fengyg
     * @date 2017-06-16
     */
    public List<ExpStock> autoCompleteStockList(String q,String limit,String storageId){
        String orgId = UserUtils.getOrgId();
        return expStockDao.autoCompleteStockList(q,limit,orgId, storageId);
    }


    /**
     * 消耗品自动补全
     * @param orgId 机构id
     * @param q 输入码
     * @param limit 条数
     * @return
     * @author zhangyao
     * @date 2017-07-19
     */
    public List<BaseDto> automatic(String orgId,String q,String limit,String storageCode) {
        return expStockDao.automatic(orgId,q,limit,storageCode);
    }


}